#include <gtest/gtest.h>

#include "helper/sqlite/MemoryDB.h"
#include "helper/sqlite/AutoDBDecorator.h"
TEST(AutoDBDecoratorTest, use){
  helper::sqlite::MemoryDB mdb;
  ASSERT_TRUE(!mdb.isOpened());

  {
    helper::sqlite::AutoDBDecorator db(mdb);
    ASSERT_TRUE(db.isOpened());
  }

  ASSERT_TRUE(!mdb.isOpened());
}


#include "helper/sqlite/AutoDB.h"
#include "helper/sqlite/Statement.h"
TEST(AutoDBTest,  frame){
  {
    auto && db = helper::sqlite::AutoDB::make_memory();
    ASSERT_TRUE(db.ref().isOpened());

    std::error_code ec;
    auto && stmt = db.ref().createStatement("create table if not exists tab1 (one text primary key, two int);", ec);
    ASSERT_EQ(0, ec.value());
  }
}

TEST(AutoDBTest, move){
  auto && db = helper::sqlite::AutoDB::make_memory();
  ASSERT_TRUE(db);
  ASSERT_TRUE(db.ref().isOpened());

  auto new_auto_db = std::move(db);
  ASSERT_TRUE(new_auto_db && !db);

  std::error_code ec;
  auto && stmt = new_auto_db.ref().createStatement("create table if not exists tab1 (one text primary key, two int);", ec);
  ASSERT_EQ(0, ec.value());

}





// use auto managed 
#include "helper/resource/AutoManaged.h"
template<typename T>
using  AutoManaged = helper::resource::AutoManaged<T>;

#include "helper/sqlite/FileDB.h"
TEST(DB_AutoManagedTest, use){
  const char * url = "test_auto_managed_db.db";
  auto && db = helper::resource::make_auto_managed<helper::sqlite::FileDB>(url);
  ASSERT_TRUE(db);
  ASSERT_TRUE(db.ref().isOpened());
  ASSERT_TRUE(db.ref().exists());

  { // ddl 
    std::error_code ec;
    auto && stmt = db.ref().createStatement("create table tab1 (one text primary key, two int);", ec);
    ASSERT_TRUE(stmt && !ec);

    auto && r = stmt->execute();
    ASSERT_TRUE(r);
    ASSERT_EQ(0, r.affectRows());
  }
  ASSERT_EQ(std::error_code(), db.ref().destroy());
}
